<script setup lang="ts">
import { onMounted, Ref } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage, ElMessageBox } from "element-plus";
import useShopCartStore from "@/pinia/modules/shopCartStore/shopCartStore.ts";
import useDetailStore from "@/pinia/modules/detailStore/detailStore.ts";
import type { ShopCart } from "@/types/shopCartTypes/shopCartTypes.ts";
import Relevant from "@/views/detail/components/relevant/relevant.vue";
import Empty from "@/views/shopCart/components/empty/empty.vue";
import CartSku from "@/views/shopCart/components/cartSku/cartSku.vue";
import { selectSku } from "@/types/detailTypes/detailTypes.ts";
import { getUserInfo } from "@/utils/localStorage.ts";
import { Router, useRouter } from "vue-router";

const router: Router = useRouter();
const shopCartStore = useShopCartStore();
const detailStore = useDetailStore();
const { validShopCartList, inValidShopCartList, validShopCartListTotal, isSelectAll, selectValidShopCartListTotal, selectAmount, selectValidShopCartList } = storeToRefs(shopCartStore);
const { relevantList }: { relevantList: Ref<any[]> } = storeToRefs(detailStore);
const changeSelectAll = (checked: boolean) => {
   shopCartStore.changeSelectAll(checked);
};
const changeSelect = (checked: boolean, skuId: string) => {
   shopCartStore.changeSelect(checked, skuId);
};
const deleteGood = async (good: ShopCart) => {
   const confirm = await ElMessageBox.confirm(`确定删除${good.name}吗?`, "提示").catch(error => error);
   if (confirm === "cancel") return;
   await shopCartStore.deleteShopCart(good.skuId);
};
const handleDeleteSelect = async () => {
   const confirm = await ElMessageBox.confirm(`确定删除选中的商品吗?`, "提示").catch(error => error);
   if (confirm === "cancel") return;
   shopCartStore.deleteSelect();
};
const handleDeleteEffectiven = async () => {
   const confirm = await ElMessageBox.confirm(`确定删除失效的商品吗?`, "提示").catch(error => error);
   if (confirm === "cancel") return;
   shopCartStore.deleteEffectiven();
};
const changeCount = (good: ShopCart, count: number) => {
   shopCartStore.changeCount(good.skuId, count);
};
const updateSku = (newSkuInfo: selectSku, oldSkuId: string) => {
   shopCartStore.updateSku({ newSkuInfo, oldSkuId });
};

const handleCheckOut = async () => {
   if (!selectValidShopCartList.value.length) return ElMessage.error("请选择需要结算的商品");
   if (getUserInfo()) {
      router.push({ path: "/member/checkout" });
   } else {
      const confirm: string = await ElMessageBox.confirm("没有登录确定登录吗?", "提示").catch(error => error);
      if (confirm === "cancel") return;
      router.push({ path: "/member/checkout" });
   }

};

onMounted(() => {
   detailStore.fetchRelevantList(undefined, 16);
});

</script>

<template>
   <div class="shop-cart">
      <div class="container">
         <Breadcrumb>
            <BreadcrumbItem to="/">首页</BreadcrumbItem>
            <BreadcrumbItem>购物车</BreadcrumbItem>
         </Breadcrumb>
         <div class="cart">
            <table v-if="validShopCartList.length">
               <thead>
               <tr>
                  <th width="120">
                     <Checkbox :modelValue="isSelectAll" @change="changeSelectAll">全选</Checkbox>
                  </th>
                  <th width="400">商品信息</th>
                  <th width="220">单价</th>
                  <th width="180">数量</th>
                  <th width="180">小计</th>
                  <th width="140">操作</th>
               </tr>
               </thead>
               <!-- 有效商品 -->
               <tbody>
               <transition-group name="list">
                  <tr v-for="(item) in validShopCartList" :key="item.skuId">
                     <td>
                        <Checkbox :modelValue="item.selected" @change="changeSelect(!item.selected,item.skuId)" />
                     </td>
                     <td>
                        <div class="goods">
                           <RouterLink to="/"><img :src="item.picture" alt=""></RouterLink>
                           <div>
                              <p class="name ellipsis">{{ item.name }}</p>
                              <!-- 选择规格组件 -->
                              <cart-sku :attr-text="item.attrsText" :sku-id="item.skuId" @change="(skuInfo)=>updateSku(skuInfo,item.skuId)"></cart-sku>
                           </div>
                        </div>
                     </td>
                     <td class="tc">
                        <p>{{ item.nowPrice }}</p>
                        <p v-if="item.nowPrice-item.price>0">比加入时降价<span class="red">{{ item.nowPrice - item.price }}</span></p>
                     </td>
                     <td class="tc">
                        <Count :modelValue="item.count" :max="item.stock" @change="(count:number)=>changeCount(item,count)" />
                     </td>
                     <td class="tc"><p class="f16 red">{{ item.nowPrice * item.count }}</p></td>
                     <td class="tc">
                        <p><a class="green" @click="deleteGood(item)">删除</a></p>
                     </td>
                  </tr>
               </transition-group>
               </tbody>
               <!-- 无效商品 -->
               <tbody v-if="inValidShopCartList.length">
               <tr>
                  <td colspan="6"><h3 class="tit">失效商品</h3></td>
               </tr>
               <tr v-for="(item) in inValidShopCartList" :key="item.skuId">
                  <td>
                     <Checkbox style="color:#eee;" :modelValue="item.selected" />
                  </td>
                  <td>
                     <div class="goods">
                        <RouterLink to="/"><img :src="item.picture" alt=""></RouterLink>
                        <div>
                           <p class="name ellipsis">{{ item.name }}</p>
                           <p class="attr">{{ item.attrsText }}</p>
                        </div>
                     </div>
                  </td>
                  <td class="tc"><p>{{ item.nowPrice }}</p></td>
                  <td class="tc">{{ item.count }}</td>
                  <td class="tc"><p>{{ item.nowPrice * item.count }}</p></td>
                  <td class="tc">
                     <p><a class="green">删除</a></p>
                  </td>
               </tr>
               </tbody>
            </table>
            <!--空购物车-->
            <empty v-else></empty>
         </div>
         <!-- 操作栏 -->
         <div class="action" v-if="validShopCartList.length">
            <div class="batch">
               <Checkbox :modelValue="isSelectAll" @change="changeSelectAll">全选</Checkbox>
               <a @click="handleDeleteSelect">删除选中商品</a>
               <a @click="handleDeleteEffectiven">清空失效商品</a>
            </div>
            <div class="total">
               <span>共 {{ validShopCartListTotal }} 件商品，已选择 {{ selectValidShopCartListTotal }} 件，商品合计:</span>
               <span class="red">¥{{ selectAmount }}</span>
               <Button type="primary" size="middle" @click="handleCheckOut">下单结算</Button>
            </div>
         </div>
         <!-- 猜你喜欢 -->
         <Relevant :list="relevantList" />
      </div>
   </div>
</template>

<style scoped lang="less">
.tc {
   text-align: center;

   .xtx-numbox {
      margin: 0 auto;
      width: 120px;
   }
}

.red {
   color: @priceColor;
}

.green {
   color: @xtxColor
}

.f16 {
   font-size: 16px;
}

.goods {
   display: flex;
   align-items: center;

   img {
      width: 100px;
      height: 100px;
   }

   > div {
      width: 280px;
      font-size: 16px;
      padding-left: 10px;

      .attr {
         font-size: 14px;
         color: #999;
      }
   }
}

.action {
   display: flex;
   background: #fff;
   margin-top: 20px;
   height: 80px;
   align-items: center;
   font-size: 16px;
   justify-content: space-between;
   padding: 0 30px;

   .xtx-checkbox {
      color: #999;
   }

   .batch {
      a {
         margin-left: 20px;
      }
   }

   .red {
      font-size: 18px;
      margin-right: 20px;
      font-weight: bold;
   }
}

.tit {
   color: #666;
   font-size: 16px;
   font-weight: normal;
   line-height: 50px;
}

.shop-cart {
   .cart {
      background: #fff;
      color: #666;

      table {
         border-spacing: 0;
         border-collapse: collapse;
         line-height: 24px;

         th, td {
            padding: 10px;
            border-bottom: 1px solid #f5f5f5;

            &:first-child {
               text-align: left;
               padding-left: 30px;
               color: #999;
            }
         }

         th {
            font-size: 16px;
            font-weight: normal;
            line-height: 50px;
         }
      }
   }
}

</style>
